<template>
  <div>

    <!-- 查询条件表单 -->
    <div class="query-form">
      <a-form ref="formRef" :model="queryForm" label-align="left" auto-label-width>
        <a-row justify="start" :gutter="16">
          <a-col :span="6">
            <a-form-item field="dictName" :label="$t('dict.columns.dictName')">
              <a-input v-model="queryForm.username"
                :placeholder="$t('common.inputPlaceholder') + $t('dict.columns.dictName')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="dictType" :label="$t('dict.columns.dictType')">
              <a-input v-model="queryForm.nickName"
                :placeholder="$t('common.inputPlaceholder') + $t('dict.columns.dictType')" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="status" :label="$t('common.status')">
              <a-select v-model="queryForm.status" allow-clear :options="statusOption"
                :placeholder="$t('common.selectPlaceholder') + $t('common.status')" />
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
      <div>
        <!-- 查询按钮 -->
        <a-button-group>
          <a-button type="primary" @click="search">{{ t('common.search') }}</a-button>
          <a-button @click="clear">{{ t('common.clear') }}</a-button>
        </a-button-group>
      </div>
    </div>

    <!-- 数据表格 -->
    <a-table ref="tableRef" :columns="columns" :data="tableData" :pagination="false" stripe table-layout-fixed
      row-key="id" @select="onSelect" :selected-keys="selectedKeys" :row-selection="rowSelection">
      <template #status="{ record }">
        <a-switch v-model="record.status" :checked-value="1" :unchecked-value="0"
          @change="onStatusChange(record)"></a-switch>
      </template>
      <template #optional="{ record }">
        <a-button type="text" size="small" @click="openEditModal(record)" :title="$t('common.edit')">
          <template #icon>
            <icon-edit />
          </template>
        </a-button>
        <a-button @click="openDictItemEditModal(record)" type="text" :title="$t('dict.actions.manageDictItem')">
          <template #icon>
            <icon-ordered-list />
          </template>
        </a-button>
        <a-popconfirm :content="$t('common.deleteTip')" @ok="remove(record)">
          <a-button type="text" :title="$t('common.remove')" status="danger">
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </a-popconfirm>
      </template>
      <template #footer>
        <div class="table-footer">
          <a-button-group>
            <a-button type="primary" @click="openEditModal()">
              <template #icon>
                <icon-plus />
              </template>
              {{ t('common.add') }}</a-button>
            <!-- <a-button @click="clear">
                          <template #icon>
                              <icon-upload />
                          </template>
                          {{ t('common.importFile') }}</a-button>
                      <a-button @click="clear">
                          <template #icon>
                              <icon-download />
                          </template>
                          {{ t('common.exportFile') }}</a-button> -->

            <a-popconfirm :content="$t('common.deleteTip')" @ok="remove">
              <a-button status="danger" :disabled="selectedKeys.length === 0">
                <template #icon>
                  <icon-delete />
                </template>
                {{ t('common.batchDelete') }}</a-button>
            </a-popconfirm>

          </a-button-group>

          <a-pagination v-bind="queryForm.page" show-total @change="changePage" show-page-size
            :page-size-options="pageSizeOptions" @page-size-change="(pageSize) => {
              queryForm.page.pageSize = pageSize
              search()
            }" />
        </div>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal v-model:visible="modalVisiable" :on-before-ok="handleOk" @cancel="closeEditModal" @close="closeEditModal">
      <template #title>
        {{ dataFormTitle }}
      </template>
      <a-form :model="dataForm" ref="dataFormRef" :rules="dataFormRules">
        <a-form-item field="dictName" :label="$t('dict.columns.dictName')">
          <a-input v-model="dataForm.dictName"
            :placeholder="$t('common.inputPlaceholder') + $t('dict.columns.dictName')" />
        </a-form-item>
        <a-form-item field="dictType" :label="$t('dict.columns.dictType')">
          <a-input v-model="dataForm.dictType"
            :placeholder="$t('common.inputPlaceholder') + $t('dict.columns.dictType')" />
        </a-form-item>
        <a-form-item field="remark" :label="$t('dict.columns.remark')">
          <a-input v-model="dataForm.remark" :placeholder="$t('common.inputPlaceholder') + $t('dict.columns.remark')" />
        </a-form-item>
        <a-form-item field="status" :label="$t('common.status')">
          <a-switch v-model="dataForm.status" :checked-value="1" :unchecked-value="0"></a-switch>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增/编辑弹窗 -->
    <a-modal width="1000px" v-model:visible="dictItemModalVisiable" :on-before-ok="handleEditDictOk"
      @cancel="closeEditModal" @close="closeEditModal">
      <template #title>
        {{ dataFormTitle }}
      </template>
      <div style="margin-bottom: 10px">
        <a-button @click="addDictItem" type="primary">
          {{ t('common.add') }}
          <template #icon>
            <icon-plus />
          </template>
        </a-button>
      </div>
      <a-table ref="dictItemTableRef" :columns="dictItemColumns" :data="dictItemTableData" :pagination="false" stripe
        table-layout-fixed>
        <template #dictLabel="{ record }">
          <a-input v-model="record.dictLabel" placeholder="请输入字典标签" />
        </template>
        <template #dictValue="{ record }">
          <a-input v-model="record.dictValue" placeholder="请输入字典值" />
        </template>
        <template #isDefault="{ record }">
          <a-checkbox v-model="record.isDefault" @change="onDefaultChange(record)"></a-checkbox>
        </template>
        <template #status="{ record }">
          <a-switch type="line" v-model="record.status" :checked-value="1" :unchecked-value="0" />
        </template>
        <template #remark="{ record }">
          <a-input v-model="record.remark" placeholder="请输入备注" />
        </template>
        <template #optional="{ record }">
          <a-button @click="deleteDictItem(record)" type="text" status="danger" :title="t('common.remove')">
            <template #icon>
              <icon-delete />
            </template>
          </a-button>
        </template>
      </a-table>
    </a-modal>

  </div>
</template>
<script setup>
import { pageSizeOptions } from '@/config/constants';
import { table, show, options, logicalDel, save, changeStatus, saveItems } from '@/api/dict.js'
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Message } from '@arco-design/web-vue'
const { t } = useI18n()

// 表格字段
const columns = [{
  title: t('dict.columns.dictName'),
  dataIndex: 'dictName',
  width: 200
}, {
  title: t('dict.columns.dictType'),
  dataIndex: 'dictType',
  width: 150
}, {
  title: t('dict.columns.remark'),
  dataIndex: 'remark'
},
{
  title: t('common.status'),
  slotName: 'status',
},
{
  title: t('common.createTime'),
  dataIndex: 'createTime',
  width: 200
},
{
  title: t('common.updateTime'),
  dataIndex: 'updateTime',
  width: 200
},
{
  title: t('common.optional'),
  fixed: 'right',
  slotName: 'optional',
  width: 150
}];
const dictItemColumns = [{
  title: t('dict.columns.dictItemLabel'),
  slotName: 'dictLabel',
}, {
  title: t('dict.columns.dictItemValue'),
  slotName: 'dictValue',
}, {
  title: t('dict.columns.dictDefault'),
  slotName: 'isDefault',
},
{
  title: t('common.status'),
  slotName: 'status',
}, {
  title: t('dict.columns.remark'),
  slotName: 'remark',
  width: 300
},
{
  title: t('common.optional'),
  slotName: 'optional',
  width: 80
}];

// 表格多选
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
const selectedKeys = ref([])
const onSelect = (rowKeys) => {
  selectedKeys.value = rowKeys
}
// 表格数据
const editType = ref()
const tableData = ref()
const tableRef = ref()
const dictItemTableData = ref([])
const dictItemTableRef = ref()
const deleteDictItem = (row) => {
  dictItemTableData.value = dictItemTableData.value.filter(item => item !== row)
}
const onDefaultChange = (row) => {
  dictItemTableData.value.forEach(item => item.isDefault = false)
  row.isDefault = true
}
const addDictItem = () => {
  dictItemTableData.value.push({
    dictType: editType.value,
    dictLabel: '',
    dictValue: '',
    isDefault: false,
    status: 1,
    remark: ''
  })
}
// 查询表单
const formRef = ref()
// 查询表单条件
const queryForm = reactive({
  username: '',
  realName: '',
  status: null,
  page: {
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: true
  }
})
const expandable = reactive({
  title: 'Expand',
  width: 80,
  expandedRowRender: (record) => {
    if (record.key === '3') {
      return `My Name is ${record.name}`
    }
  }
});

// 查询表格数据
const search = () => {
  let searchParams = []
  if (queryForm.username) {
    searchParams.push(
      {
        "column": "username",
        "operator": "LIKE",
        "value": queryForm.username,
      }
    )
  }
  if (queryForm.realName) {
    searchParams.push(
      {
        "column": "realName",
        "operator": "LIKE",
        "value": queryForm.realName,
      }
    )
  }
  if (queryForm.status) {
    searchParams.push(
      {
        "column": "status",
        "operator": "EQ",
        "value": queryForm.status,
      }
    )
  }
  let params = {
    "searchParams": searchParams
  }
  table(params).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records
      queryForm.page.current = res.data.current
      queryForm.page.pageSize = res.data.size
      queryForm.page.total = res.data.total
    } else {
      Message.error(res.message)
    }
  })
}
// 清空查询条件
const clear = () => {
  formRef.value.resetFields()
}

// 加载字典信息
const statusOption = ref([])
const loadDict = (dictType) => {
  options({ dictType: dictType }).then(res => {
    if (res.code === 200) {
      statusOption.value = res.data
    }
  })
}

const onStatusChange = async (record) => {
  const res = await changeStatus({ id: record.id, status: record.status })
  if (res.code === 200) {
    return true
  } else {
    search()
    Message.error(res.message)
    return false
  }
}

// 新增/编辑弹窗
let dataForm = ref({})
const dataFormRef = ref()
const dataFormTitle = ref('')
const modalVisiable = ref(false)
const dictItemModalVisiable = ref(false)
const dataFormRules = {
  dictType: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('dict.columns.dictType'),
    },
  ],
  dictName: [
    {
      required: true,
      message: t('common.inputPlaceholder') + t('dict.columns.dictName'),
    }
  ],
}

// 打开新增/编辑弹窗
const openEditModal = (item) => {
  if (item) {
    show({ id: item.id }).then(res => {
      if (res.code === 200) {
        dataForm.value = res.data
        modalVisiable.value = true
      } else {
        Message.error(res.message)
      }
    })
    dataFormTitle.value = t('common.edit')
  } else {
    dataFormTitle.value = t('common.add')
    modalVisiable.value = true
  }
}

const openDictItemEditModal = (item) => {
  dictItemTableData.value = Object.assign([], item.dataList)
  dictItemModalVisiable.value = true
  editType.value = item.dictType
}
const handleEditDictOk = async () => {
  return await new Promise((resolve) => {
    dictItemTableData.value.forEach((item, index) => {
      item.dictSort = index
    })
    saveItems(editType.value, dictItemTableData.value).then(res => {
      if (res.code === 200) {
        Message.success(t('common.operateSuccess'))
        dictItemModalVisiable.value = false
        search()
        resolve(true)
      } else {
        Message.error(res.message)
        resolve(false)
      }
    })
  })
}
const handleOk = async () => {
  return await new Promise((resolve) => {
    dataFormRef.value.validate((values) => {
      if (!values) {
        // 验证通过
        save(dataForm.value).then(res => {
          if (res.code === 200) {
            Message.success(t('common.operateSuccess'))
            modalVisiable.value = false
            search()
            resolve(true)
          } else {
            Message.success(res.message)
            resolve(false)
          }
        })
      } else {
        resolve(false)
      }
    })
  })
}
openEditModal// 关闭新增/编辑弹窗
const closeEditModal = () => {
  dataFormRef.value.resetFields()
  dataForm.value = {}
  modalVisiable.value = false
}

const remove = (item) => {
  let deleteIds = []
  if (item) {
    // 单个删除
    deleteIds.push(item.id)
  } else {
    deleteIds = [...selectedKeys.value]
  }
  if (deleteIds.length === 0) {
    Message.warning(t('common.chooseDeleteItem'))
    return
  }
  logicalDel({ ids: deleteIds }).then(res => {
    if (res.code === 200) {
      Message.success(t('common.operateSuccess'))
      search()
    } else {
      Message.error(res.message)
    }
  })
}


onMounted(() => {
  loadDict('status')
  search()
})


const changePage = (current) => {
  queryForm.page.current = current
  search()
}
</script>
<style lang="less"></style>